package com.ruoci.redis.utils.rsa;

import lombok.extern.slf4j.Slf4j;

import javax.crypto.Cipher;
import javax.crypto.spec.IvParameterSpec;
import javax.crypto.spec.SecretKeySpec;
import java.nio.charset.StandardCharsets;

/**
 * AES加密解密主类
 */
@Slf4j
public class AESUtils {

    /**
     * 用于加密和解密的AES密钥
     */
    private static final String secretKey = "c53c74968e6d08225c18a1384067f0c0";

    /**
     *  初始化向量IV
     */
    private static final String secretIv = "3d601250d91bcd433a43bcac0e54da51";
    /**
     * 定义AES算法名称
     */
    private static final String ALGORITHM = "AES";


    /**
     * 将字节数组转换为十六进制字符串
     *
     * @param bytes
     * @return
     */
    public static String bytesToHex(byte[] bytes) {
        StringBuilder hexString = new StringBuilder(2 * bytes.length);
        for (byte b : bytes) {
            String hex = Integer.toHexString(0xff & b);
            if (hex.length() == 1) {
                hexString.append('0');
            }
            hexString.append(hex);
        }
        return hexString.toString();
    }

    /**
     * 将十六进制字符串转换为字节数组
     *
     * @param hex
     * @return
     */
    public static byte[] hexToBytes(String hex) {
        int length = hex.length();
        byte[] bytes = new byte[length / 2];
        for (int i = 0; i < length; i += 2) {
            bytes[i / 2] = (byte) ((Character.digit(hex.charAt(i), 16) << 4)
                    + Character.digit(hex.charAt(i + 1), 16));
        }
        return bytes;
    }


    /**
     * 加密方法
     * @param plainText 要加密的明文
     * @return 加密后的十六进制字符串
     */
    public static String encrypt(String plainText) {
        try {
            byte[] keyBytes = hexToBytes(secretKey);
            byte[] ivBytes = hexToBytes(secretIv);
            SecretKeySpec keySpec = new SecretKeySpec(keyBytes, ALGORITHM);
            IvParameterSpec ivParameterSpec = new IvParameterSpec(ivBytes);
            Cipher cipher = Cipher.getInstance("AES/CBC/PKCS5Padding");
            cipher.init(Cipher.ENCRYPT_MODE, keySpec, ivParameterSpec);
            byte[] encryptedBytes = cipher.doFinal(plainText.getBytes(StandardCharsets.UTF_8));
            return bytesToHex(encryptedBytes);
        } catch (Exception e) {
            log.error(e.getMessage(), e);
            throw new RuntimeException("encryption error:{}" + e.getMessage(), e);
        }
    }

    /**
     * 解密方法
     * @param cipherText 加密后的十六进制字符串
     * @return 解密后的明文
     */
    public static String decrypt(String cipherText) {
        try {
            byte[] keyBytes = hexToBytes(secretKey);
            byte[] ivBytes = hexToBytes(secretIv);
            SecretKeySpec keySpec = new SecretKeySpec(keyBytes, ALGORITHM);
            IvParameterSpec ivParameterSpec = new IvParameterSpec(ivBytes);
            Cipher cipher = Cipher.getInstance("AES/CBC/PKCS5Padding");
            cipher.init(Cipher.DECRYPT_MODE, keySpec, ivParameterSpec);
            byte[] decryptedBytes = cipher.doFinal(hexToBytes(cipherText));
            return new String(decryptedBytes, StandardCharsets.UTF_8);
        } catch (Exception e) {
            log.error(e.getMessage(), e);
            throw new RuntimeException("decryption error:{}" + e.getMessage(), e);
        }
    }


    public static void main(String[] args) {
        String encrypt = AESUtils.encrypt("加密测试");
        System.out.println(encrypt);
        String decrypt = AESUtils.decrypt(encrypt);
        System.out.println(decrypt);
    }

}
